//index.js
//获取应用实例
var app = getApp()
const config = require('../../config');
const host = config.host;
Page({
  data: {
    userInfo: {},
    goodsList:[],
    loadTime:0,
    page:1,
    buyGoodsID:null,// 出价商品id
    buyGoodsPrice:null,// 价格
    buyBoxStatus:false,// 是否显示出价输入框
    webUserInfo:null, // 用户站点信息
    mobileInputStatus: true, // 绑定手机框
    newMobile: null,
    newUsername:null,
    newAddress:null,
    newLinkman:null,
    newCategory:null,
    categoryIndex:-1,
    categorylist: [{ id: 1, name: "水发豆制品类" }, { id: 2, name: "水果类" }, { id: 3, name: "牛羊肉类" }, { id: 4, name: "百货耗材类" }, { id: 5, name: "禽蛋类" }, { id: 6, name: "粮油干调类" }, { id: 7, name:"蔬菜类"}]

  },
  onLoad: function () {
    var that = this
    // 加载商品
    console.log(1);
    
  },
  onReady:function(){
  },
  onShow:function(){
    var that = this
    if (app.globalData.webUserInfo !=null){
      // 每次显示页面都去更新用户最新信息
      app.getWebUserInfo(app.globalData.userInfo.openID, app.globalData.userInfo.nickName, app.globalData.userInfo.avatarUrl, function (webUserInfo) {
        if (webUserInfo.address && webUserInfo.categoryId && webUserInfo.linkman && webUserInfo.mobile && webUserInfo.username) {
          that.setData({
            webUserInfo: webUserInfo
          })
          that.getGoodsList();
        }
      })
    }else{
      //调用应用实例的方法获取全局数据
      app.getUserInfo(function (userInfo) {
        //更新数据 open
        that.setData({
          userInfo: userInfo
        })
        app.globalData.userInfo = userInfo
        // 获取用openid
        app.getOpenID(function (openID) {
          var nickName = userInfo.nickName
          var headPic = userInfo.avatarUrl
          // 获取用户在站点的信息
          app.getWebUserInfo(openID, nickName, headPic, function (webUserInfo) {
            if (webUserInfo) {
              if(webUserInfo.address && webUserInfo.categoryId && webUserInfo.linkman && webUserInfo.mobile && webUserInfo.username){
                that.setData({
                  webUserInfo: webUserInfo
                })
                that.getGoodsList();
              }else{
                that.setData({
                  mobileInputStatus:!that.data.mobileInputStatus
                })
              }
            }
          })
        })
      })
    }
  },
  /**
   * 获取商品列表
   */
  getGoodsList: function (page){
    var that = this
    console.log("that.data.webUserInfo.categoryId",that.data.webUserInfo.categoryId);
    wx.request({
      url: host +'/wxapp/goods/getGoodsList',
      data: {
        cateID:that.data.webUserInfo.categoryId,
				page: that.data.page
      },
      header: { 'content-type': 'application/json'},
      method: 'GET',
      dataType: 'json',
      success: function(res) {
        if (res.data.ok == true) {
          that.setData({
            loadTime:that.data.loadTime+1
          })     //加载时间
          var list = that.data.goodsList;
					for (var i = 0; i < res.data.content.goodsList.content.length; i++) {
						list.push(res.data.content.goodsList.content[i]);
          }
          that.setData({
            goodsList: list
          })
          console.log(that.data.goodsList);
        } else {
          wx.showToast({
            title: '没有更多了',
            image: "../../images/error2.png"
          })
        }
      },
      fail: function(res) {
        console.log(1)
      },
      complete: function(res) {},
    })
  },
  /**
   * 点击出价
   */
  doBuy:function(e){
    var that = this
    var goodsID = e.detail.value.goodsID
		that.setData({
			buyGoodsPrice: null,
		})

    if (app.globalData.webUserInfo.deposit){
      // 如果用户信息存在，收集formid
      var formID = e.detail.formId;
      if (formID != "the formId is a mock one"){
        app.collectFormID(formID)
      }

      if (app.globalData.webUserInfo.mobile && app.globalData.webUserInfo.username && app.globalData.webUserInfo.address){
        that.setData({
          buyBoxStatus: true,
          buyGoodsID: goodsID,
        })
      }else{
        that.setData({
          newMobile: null,
          mobileInputStatus: !that.data.mobileInputStatus,
        })
      }
    }else{
      wx.showModal({
        title: '提示',
        content: '请先交保证金！',
        success:function(res){
          if (res.confirm) {
						app.payDeposit()
          }
        }
      })
    }
  },
  /**
   * 确认出价点击发送
   */
  sendPrice:function(){
    var that = this
		var goodsPrice = that.data.buyGoodsPrice
		if (that.data.webUserInfo){
      console.log(21);
			var uid = that.data.webUserInfo.id
			var goodsID = that.data.buyGoodsID
			app.doSendPrice(uid, goodsPrice, goodsID)
		}
  },
  /**
   * 出价失去焦点
   */
  buyBlur:function(){
    var that = this 
    that.setData({
      buyBoxStatus:0
    })
  },
  /**
   * 变更价格
   */
  changeBuyGoodsPrice:function(e){
		var that = this
		that.setData({
			buyGoodsPrice: e.detail.value
		})
  },
  bindPickerChange:function(e){
    this.setData({
      categoryIndex: e.detail.value
    })
  },
  /**
   * 变更联系电话
   */
  changeMobileInput: function (e) {
    var that = this
    var mobile = e.detail.value
    that.setData({
      newMobile: mobile
    })
  },
  /**
   * 变更联系人电话
   */
  changeLinkmanInput: function (e) {
    var that = this
    var linkman = e.detail.value
    that.setData({
      newLinkman: linkman
    })
  },
  /**
   * 变更名称
   */
  changeUsernameInput: function (e) {
    var that = this
    var username = e.detail.value
    that.setData({
      newUsername: username
    })
  },
  /**
   * 变更联系电话
   */
  changeAddressInput: function (e) {
    var that = this
    var address = e.detail.value
    that.setData({
      newAddress: address
    })
  },
  /**
   * 确认修改手机号
   */
  changeMobileConfirm: function () {
    var that = this
    console.log(that.data)
    if (that.data.categoryIndex !=-1 && that.data.newMobile && that.data.newUsername && that.data.newLinkman && that.data.newAddress)     {
      var pattern = /^1[3|4|5|8|9]\d{9}$/
      var flag = pattern.test(that.data.newMobile);
      if (!flag) {
        wx.showToast({
          title: '手机号格式错误！',
          image: "../../images/error2.png",
          duration: 2000
        })
        return
      }
    } else {
      wx.showToast({
        title: '请补齐信息！',
        image: "../../images/error2.png"
      })
      return
    }
    console.log("catelogryid",that.data.categorylist[that.data.categoryIndex].id);
    wx.request({
      url: host + '/wxapp/index/changeMobile',
      data: {
        categoryId: that.data.categorylist[that.data.categoryIndex].id,
        mobile: that.data.newMobile,
        username:that.data.newUsername,
        linkman:that.data.newLinkman,
        address:that.data.newAddress,
        openID: app.globalData.userInfo.openID
      },
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.ok == true) {
          that.setData({
            webUserInfo: res.data.content.userInfo,
            mobileInputStatus: !that.data.mobileInputStatus,
          })
          app.globalData.webUserInfo = res.data.content.userInfo
          
          wx.showToast({
            title: '修改成功',
          })
          that.getGoodsList();
        } else {
          wx.showToast({
            title: '修改失败！',
            image: "../../images/error2.png"
          })
        }
      }
    })
  },
  /**
   * 取消修改
   */
  changeMobileCancel: function () {
    var that = this
    that.setData({
      newMobile: null,
      mobileInputStatus: !that.data.mobileInputStatus,
    })
  },
 
	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh: function () {
		var that = this
		that.setData({
			goodsList:[],
			page:1,
		})
		that.getGoodsList()
    wx.stopPullDownRefresh()
	},
	/**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("到底了")
		var that = this
		that.setData({
			page: that.data.page + 1
		})
		var page = that.data.page
		that.getGoodsList(page)
	},
  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () {
    app.sendFormIDs()
    console.log("隐藏index")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.sendFormIDs()
    console.log("卸载index")
  },
})
